import { useState,useReducer } from "react"

function reducer(state,action){
    switch(action.type){
      case 'INC':
        return state+1
      case 'DEC':
        return state-1
      case 'SET':
        return state+action.payload
      default:
        return state
    }
}

const UseReducer=()=>{
    const [state,dispatch]=useReducer(reducer,0)
  const [n,setN]=useState(0)
  const handleInputChange=(data)=>{
    // 控制台打印传入参数以找到value位置
    console.log(data)
    // 加号变字符串为数字
    setN(+data.target.value)
  }

  const [state2,setState2]=useState(0)
  const [n2,setN2]=useState(0)
  const handleInputChange2=(data)=>{
    // 控制台打印传入参数以找到value位置
    console.log(data)
    // 加号变字符串为数字
    setN2(+data.target.value)
  }

  return (
    <div>
      <button onClick={()=>dispatch({type:'DEC'})}>-</button>
      state={state}
      <button onClick={()=>dispatch({type:'INC'})}>+</button>
      <input type="number" onChange={handleInputChange}/>
      <button onClick={()=>dispatch({type:'SET',payload:n})}>+{n}</button>
      <br />
      <button onClick={()=>setState2(reducer(state2,{type:'DEC'}))}>-</button>
      state2={state2}
      <button onClick={()=>setState2(reducer(state2,{type:'INC'}))}>+</button>
      <input type="number" onChange={handleInputChange2}/>
      <button onClick={()=>setState2(reducer(state2,{type:'SET',payload:n2}))}>+{n2}</button>

    </div>
  )
}

export default UseReducer